package com.itheima.controller;

import com.itheima.Context.BaseContext;
import com.itheima.utils.JwtUtils;
import com.itheima.pojo.entity.Emp;
import com.itheima.pojo.vo.LoginVo;
import com.itheima.pojo.vo.Result;
import com.itheima.service.EmpService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private EmpService empService;

    @PostMapping
    public Result login(@RequestBody Emp emp) {
        Emp loginEmp = empService.checkLogin(emp);
        BaseContext.setCurrentId(loginEmp.getId());
        Map<String,Object> claims = new HashMap<>();
        claims.put("username",emp.getUsername());
        claims.put("name",emp.getName());
        claims.put("id",loginEmp.getId());
        String token = JwtUtils.generateJwt(claims);

        LoginVo loginVo = new LoginVo();
        BeanUtils.copyProperties(loginEmp,loginVo);//
        loginVo.setToken(token);
        return Result.success(loginVo);
    }
}
